package myJs.user.data

import myJs.Implicits._
import myJs.Utils._
import scala.scalajs.js.Dynamic.{global=>g}
import myJs.myPkg._
import myJs.myPkg.jquery._
import myJs.tool.Tool
import myJs.tool.Tool._
import org.scalajs.dom.ext.Ajax
import scalatags.Text.all._

import scala.scalajs.js
import scala.scalajs.js.annotation.{JSExport, JSExportTopLevel}
import org.scalajs.macrotaskexecutor.MacrotaskExecutor.Implicits._

/**
 * Created by yz on 2019/4/25
 */
@JSExportTopLevel("VarInfoDataDetail")
object VarInfoDataDetail {
  val tableId = "table"

  @JSExport("init")
  def init = {
    viewShow(getId)
  }

  def getId = {
    g.id.toString
  }

  @JSExport("viewShow")
  def viewShow(id: String) = {
    val url = g.jsRoutes.controllers.VarInfoFileDataController.getFileDataById().url.toString
    Ajax.get(url = s"${url.noCache}&id=${id}", headers = Map("Content-Type" -> "application/json")).map { xhr =>
      val dict = xhr.responseText.toJDJAn
      dict.foreach { case (k, v) =>
        val trueV = k match {
          case "size" => span(Tool.getFileSize(v))
          case "fileName" => span(v.toString)
          case "tags" => span(Tool.tagMap(v.toString))
          case _ => span(v.toString)
        }
        $(s"#fileInfo #${k}").html(trueV.render)
      }
      refreshData(dict("id").toString, dict("fileName").toString)
    }
  }

  def refreshData(id: String, fileName: String) = {
    val index = layer.alert(Tool.loadingElement, Tool.layerOptions)
    val url = g.jsRoutes.controllers.VarInfoFileDataController.getFileData().url.toString
    Ajax.get(url = s"${url.noCache}&id=${id}", headers = Map("Content-Type" -> "application/json")).map { xhr =>
      val rs = xhr.responseText.toJDJAn
      val columnNames = rs("columnNames").asInstanceOf[js.Array[String]]
      val columns = columnNames.map { columnName =>
        val fmt = columnName
        ColumnOptions.field(columnName).title(columnName).sortable(true)
      }
      val exportOptions = ExportOptions.fileName(fileName).csvSeparator("\t").csvEnclosure("")
      val options = TableOptions.data(rs("array")).columns(columns).search(true).pagination(true).exportOptions(exportOptions).
        showExport(true).exportDataType("all").exportTypes(js.Array("txt"))
      $(s"#${tableId}").bootstrapTable(options)
      layer.close(index)
    }
  }

}
